<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="formData.supplierId" placeholder="请选择供应商">
          <el-option
            v-for="dict in supplierList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备组" prop="groupId">
        <el-select v-model="formData.groupId" placeholder="请输入设备组">
          <el-option
            v-for="dict in deviceGroups"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="formData.brand" placeholder="请输入品牌" />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input v-model="formData.model" placeholder="请输入型号" />
      </el-form-item>
      <el-form-item label="设备规格" prop="specification">
        <el-input v-model="formData.specification" placeholder="请输入设备规格" />
      </el-form-item>
      <el-form-item label="是否特种设备" prop="isSpecialEquipment">
        <el-radio-group v-model="formData.isSpecialEquipment">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.LOGIC_STATUS)" :key="dict.value"
            :value="dict.value" :label="dict.label"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="使用描述" prop="useDescribe">
        <el-input v-model="formData.useDescribe" placeholder="请输入使用描述" />
      </el-form-item>
      <el-form-item label="是否需要检修" prop="isNeedRepair">
        <el-radio-group v-model="formData.isNeedRepair">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.LOGIC_STATUS)" :key="dict.value"
            :value="dict.value" :label="dict.label"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="检修周期，单位：天" prop="repairCycle">
        <el-input v-model="formData.repairCycle" placeholder="请输入检修周期，单位：天" />
      </el-form-item>
      <el-form-item label="检修许可证" prop="repairPermitCard">
        <el-input v-model="formData.repairPermitCard" placeholder="请输入检修许可证" />
      </el-form-item>
      <el-form-item label="检修原因" prop="repairReason">
        <el-input v-model="formData.repairReason" placeholder="请输入检修原因" />
      </el-form-item>
      <el-form-item label="是否需要维护" prop="isNeedMaintain">
        <el-radio-group v-model="formData.isNeedMaintain">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.LOGIC_STATUS)" :key="dict.value"
            :value="dict.value" :label="dict.label"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="维护周期，单位：天" prop="maintainCycle">
        <el-input v-model="formData.maintainCycle" placeholder="请输入维护周期，单位：天" />
      </el-form-item>
      <el-form-item label="是否需要计量" prop="isNeedFitMetering">
        <el-radio-group v-model="formData.isNeedFitMetering">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.LOGIC_STATUS)" :key="dict.value"
            :value="dict.value" :label="dict.label"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="计量周期，单位：天" prop="fitMeteringCycle">
        <el-input v-model="formData.fitMeteringCycle" placeholder="请输入计量周期，单位：天" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DeviceApi, DeviceVO } from '@/api/zjyj/device'
import {DICT_TYPE, getDictOptions, getIntDictOptions} from "@/utils/dict";
import {SupplierApi} from "@/api/zjyj/supplier";
import {ZjyjDeviceGroupApi} from '@/api/zjyj/devicegroup';

/** 设备 表单 */
defineOptions({ name: 'DeviceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  supplierId: undefined,
  groupId: undefined,
  brand: undefined,
  model: undefined,
  specification: undefined,
  isSpecialEquipment: 0,
  useDescribe: undefined,
  isNeedRepair: undefined,
  repairCycle: undefined,
  repairPermitCard: undefined,
  repairReason: undefined,
  isNeedMaintain: undefined,
  maintainCycle: undefined,
  isNeedFitMetering: undefined,
  fitMeteringCycle: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  supplierId: [{ required: true, message: '供应商id不能为空', trigger: 'blur' }],
  groupId: [{ required: true, message: '设备组id不能为空', trigger: 'blur' }],
  brand: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  model: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
  specification: [{ required: true, message: '设备规格不能为空', trigger: 'blur' }],
  isSpecialEquipment: [{ required: true, message: '是否特种设备不能为空', trigger: 'blur' }],
  useDescribe: [{ required: true, message: '使用描述不能为空', trigger: 'blur' }],
  isNeedRepair: [{ required: true, message: '是否需要检修不能为空', trigger: 'blur' }],
  repairCycle: [{ required: true, message: '检修周期，单位：天不能为空', trigger: 'blur' }],
  repairPermitCard: [{ required: true, message: '检修许可证不能为空', trigger: 'blur' }],
  repairReason: [{ required: true, message: '检修原因不能为空', trigger: 'blur' }],
  isNeedMaintain: [{ required: true, message: '是否需要维护不能为空', trigger: 'blur' }],
  maintainCycle: [{ required: true, message: '维护周期，单位：天不能为空', trigger: 'blur' }],
  isNeedFitMetering: [{ required: true, message: '是否需要计量不能为空', trigger: 'blur' }],
  fitMeteringCycle: [{ required: true, message: '计量周期，单位：天不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const supplierList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceApi.getDevice(id)
    } finally {
      formLoading.value = false
    }
  }
  supplierList.value = (await SupplierApi.getSupplierPage({page: 1, pageSize: 9999})).list

  await getDeviceGroup();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceVO
    if (formType.value === 'create') {
      await DeviceApi.createDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const deviceGroups = ref([])
const getDeviceGroup = async () => {
  const groupData = await ZjyjDeviceGroupApi.getDeviceGroupPage({page: 1, pageSize: 9999})
  deviceGroups.value = groupData.list
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    supplierId: undefined,
    groupId: undefined,
    brand: undefined,
    model: undefined,
    specification: undefined,
    isSpecialEquipment: 0,
    useDescribe: undefined,
    isNeedRepair: undefined,
    repairCycle: undefined,
    repairPermitCard: undefined,
    repairReason: undefined,
    isNeedMaintain: undefined,
    maintainCycle: undefined,
    isNeedFitMetering: undefined,
    fitMeteringCycle: undefined
  }
  formRef.value?.resetFields()
}
</script>
